<?php
namespace app\api\controller\signreport;

use app\api\controller\Baseuser;
use app\common\model\customer\Customer;
use app\common\model\company\Company;
use app\common\model\company\CompanyTouch;
use app\common\model\company\CompanyFile;
use app\common\model\company\CompanyFileType;
use app\common\model\user\User as UserModel;
use app\common\model\signreport\Sign as SignModel;
use app\common\model\signreport\Report as ReportModel;
use app\common\model\customer\Subscribe as SubscribeModel;
use app\common\model\user\Setting;


use think\facade\Request;

class User extends Baseuser
{
    private $statusName = ['1' => '进行中', '2' => '已完成' , '3' => '已取消' ];

    // 查询可筛选用户
    public function getUserList()
    {
        // 判断是不是管理员
        $userModel = new UserModel;
        $user = $userModel->getinfo('', $this->user_id);
        if ($user &&( $user['Role'] == 204||$user['Role'] == 205)) {
            $where[] = ['Role', '>', '200'];
            // $where[] = ['UserId', '<>', $this->user_id];
            $where[] = ['State', '=', '1'];
            $data = $userModel->getUserList($where);
            $data[]=['Name'=>'所有人','UserId'=>-1];
        } else {
            $data = false;
        }
        return myok($data);
    }
    // 查询业务员列表
    public function getBussiness()
    {
        $where[] = ['Role','in','201,204,205'];
        $where[] = ['State', '=', '1'];
        $data = (new UserModel)->getUserList($where);
        return myok($data);
    }

    //查询员工
    public function getpeople(){
        $where[] = ['Role','>','200'];
        $where[] = ['State', '=', '1'];
        $data = (new UserModel)->getUserList($where);
        $data[]=['Name'=>'所有人','UserId'=>-1];
        return myok($data);
    }

    // 查询业务员绑定的客户
    public function getBussinessCustomer()
    {
        $BussinessId =  Request::instance()->param('BussinessId');
        $data = (new Customer())->where('BussinessId', $BussinessId)->select();
        return myok($data);
    }

    // 签到统计
    public function getSignStatistics()
    {
        $currentDate =  Request::instance()->param('currentDate');
        $userId = Request::instance()->param('userId');
        // 如果没有传入用户id，就查询自己数据
        if ($userId == null) {
            $userId = $this->user_id;
        }
        // 查询上午和下午打卡时间
        $sign = (new Setting())->getSetting('sign');
        $signDate = [];
        if ($sign) {
            $signDate = json_array($sign['Content'], true);
        }
        // 查询跳过日期
        $date = (new Setting())->getSetting('work');
        $workDate = [];
        if ($date) {
            $workDate = json_array($date['Content'], true);
        }
        if (isset($signDate['early']) && isset($signDate['evening']) && $workDate !=[]) {
            // 获取当月所有日期
            $months = getMonth($currentDate);
            $i = $months[0];
            $dates = [];
            do {
                $dates[] = date('Y-m-d', $i);
                $i += 24*60*60;
            } while($i < $months[1]);

            // 剔除所有周末
            if ($workDate['restDay'] == true) {
                foreach($dates as $key=>$value) {
                    $index = date('w', strtotime($value));
                    if ($index == 0 || $index == 6) {
                        unset($dates[$key]);
                    }
                }
            }
            $dates = array_values($dates);

            // 剔除所有指定日期
            if (count($workDate['dates']) > 0) {
                for($i = 0; $i < count($dates) ; $i++) {
                    foreach($workDate['dates'] as $value) {
                        if ($dates[$i] == $value['date']) {
                            unset($dates[$i]);
                            break;
                        }
                    }
                }
            }
            $signModel = new SignModel();
            $data = [
                'normal' => 0,
                'anomaly' => 0,
                'dates' => [

                ]
            ];
            foreach ($dates as $key => $value) {
                $minWhere = [];
                $maxWhere = [];
                $minTime = $value . ' ' . $signDate['early'];
                $minWhere[] = ['UId', '=', $userId];
                $minWhere[] = ['SignTime', '<=', strtotime($minTime)];
                $minWhere[] = ['SignDate', '=', strtotime($value)];
                $minSign = $signModel->where($minWhere)->order('SignTime asc')->find();
                $minLabel = false;
                if ($minSign) {
                    $minLabel = true;
                    $data['dates'][$value]['min'] = $minSign;
                } else {
                    $data['dates'][$value]['min'] = false;
                }

                $maxTime = $value . ' ' . $signDate['evening'];
                $maxWhere[] = ['UId', '=', $userId];
                $maxWhere[] = ['SignTime', '>=', strtotime($maxTime)];
                $maxWhere[] = ['SignDate', '=', strtotime($value)];
                $maxSign = $signModel->where($maxWhere)->order('SignTime desc')->find();
                $maxLabel = false;
                if ($maxSign) {
                    $maxLabel = true;
                    $data['dates'][$value]['max'] = $maxSign;
                } else {
                    $data['dates'][$value]['max'] = false;
                }

                if ($minLabel && $maxLabel) {
                    $data['normal'] += 1;
                } else {
                    $data['anomaly'] += 1;
                }
            }
            return myok($data);
        } else {
            return myerr('没有设置参数');
        }

    }

    // 日程表信息
    public function scheduleInfo()
    {
        $currentDate =  Request::instance()->param('currentDate');
        $userId = Request::instance()->param('userId');
        // 如果没有传入用户id，就查询自己数据
        if ($userId == null) {
            $userId = $this->user_id;
        }
        // 获取月份第一天和最后一天
        $months = getMonth($currentDate);
        // 获取当月的签到信息
        if($userId!=='-1'){
            $signWhere[] = ['UId', '=', $userId];
        }
        $signWhere[] = ['SignDate', 'between', [$months[0], $months[1]]];
        $signList = (new SignModel())->getList($signWhere);

        $useridlist = get_array_id($signList,'UId');
        
        // 获取当月日报周报月报信息
        if($userId!=='-1'){
            $dayWhere[] = ['UId', '=', $userId];
        }
        $dayWhere[] = ['ReportTime', 'between', [$months[0], $months[1]]];
        $reportList = (new ReportModel)->getMonthReportList($dayWhere);
        $useridlist2 = get_array_id($reportList,'UId');
        $useridlist = array_merge($useridlist,$useridlist2);

        $userlist = UserModel::where('UserId','in',$useridlist)->column('Name','UserId');
        // 筛选签到数据
        $signListCount = count($signList);
        $signIndex = [];
        // if ($signList) {
        //     for($i = 0; $i< $signListCount; $i++) {
        //         $maxArray = [];
        //         $minArray = [];
        //         for($j = 0; $j < $signListCount; $j++) {
        //             if ($i != $j && $signList[$i]['SignDate'] == $signList[$j]['SignDate'] && strtotime($signList[$i]['SignTime']) > strtotime($signList[$j]['SignTime'])) {
        //                 $minArray[] = $signList[$j];
        //             }
        //             if ($i != $j && $signList[$i]['SignDate'] == $signList[$j]['SignDate'] && strtotime($signList[$i]['SignTime']) < strtotime($signList[$j]['SignTime'])) {
        //                 $maxArray[] = $signList[$j];
        //             }
        //         }
        //         if (count($maxArray) > 0 && count($minArray) > 0) {
        //             $signIndex[] =$i;
        //         }
        //     }
        // }
        // if ($signIndex) {
        //     foreach($signIndex as $item) {
        //         unset($signList[$item]);
        //     }
        // }
        $data = [];
        if ($signList) {
            foreach($signList as $item) {
                $temp = [
                    'id' => '100' . $item['Id'],
                    'datetime' => date('Y-m-d H', strtotime($item['SignTime'])) . ':00',
                    'content' =>  $userlist[$item['UId']].'签到 ' . $item['SignTime'],
                    'bgColor' => '#389e0d',
                    'color' => '#ffffff'
                ];
                $data[] = $temp;
            }
        }
        //获取日报
        if($reportList) {
            foreach($reportList as $item) {
                $temp = [
                    'id' => '101' . $item['Id'],
                    'datetime' => date('Y-m-d H', $item['CreateTime']) . ':00',
                    'color' => '#ffffff'
                ];
                switch($item['ReportType']) {
                    case 1:
                        $temp['content'] = $userlist[$item['UId']].'日报 ' . $item['Content'];
                        $temp['bgColor'] = '#85a5ff';
                        $temp['type'] = 'report';
                        break;
                    case 2:
                        $temp['content'] = $userlist[$item['UId']].'周报 ' . $item['Content'];
                        $temp['bgColor'] = '#b37feb';
                        $temp['type'] = 'report';
                        break;
                    case 3:
                        $temp['content'] = $userlist[$item['UId']].'月报 ' . $item['Content'];
                        $temp['bgColor'] = '#5cdbd3';
                        $temp['type'] = 'report';
                        break;
                }
                $data[] = $temp;
            }
        }

        // 预约回访
        if($userId!=='-1'){
            $subWhere[] = ['BussinessId', '=', $userId];
        }
        $subWhere[] = ['SubscribeTime', 'between', [date('Y-m-d H:i:s', $months[0]), date('Y-m-d H:i:s',$months[1])]];
        $subscribeList = (new SubscribeModel)->getList($subWhere);
        $customerModel = new Customer();
        if($subscribeList) {
            //1蓝色 2绿色 3灰色
            $bgcolor = ['1'=>'#69b1ff','2'=>'#39B55A','3'=>'#F7F8FA'];
            $color=['1'=>'#ffffff','2'=>'#ffffff','3'=>'#000'];
            foreach($subscribeList as $item) {
                if(!empty($item['CustomerId'])){
                    // 查询访问客户
                    $customer = $customerModel->where('CustomerId', $item['CustomerId'])->find();
                    $temp = [
                        'id' => '102' . $item['SubscribeId'],
                        'type'=>'customer',
                        'SubscribeId'=>$item['SubscribeId'],
                        'opid'=>$item['CustomerId'],
                        'datetime' => substr($item['SubscribeTime'],0,13) . ':00',
                        'content' => '预约访问
                        企业名称：' .$customer['Name'] .'
                        联系人：'  . $customer['UserName'] .'
                        联系电话：'  . $customer['UserTel'] .'
                        地址：' . $customer['Address'] . '
                        预约时间：' . $item['SubscribeTime'] . '
                        预约回访内容：' . $item['Content']. '
                        状态：' . $this->statusName[$item['Status']],
                        'bgColor' => $bgcolor[$item['Status']],
                        'color' => $color[$item['Status']]
                    ];
                    $data[] = $temp;
                }else if(!empty($item['CompanyTouchId'])){
                    //查询企业与摸排表信息
                    $company = Company::get($item['CompanyId']);
                    $touch = CompanyTouch::get($item['CompanyTouchId']);
                    // if(empty($touch)){continue;}
                    $temp = [
                        'id' => '103' . $item['SubscribeId'],
                        'type'=>'touch',
                        'SubscribeId'=>$item['SubscribeId'],
                        'opid'=>$item['CompanyTouchId'],
                        'datetime' => substr($item['SubscribeTime'],0,13) . ':00',
                        'content' => '企业排查登记提醒
                        企业名称：' .$company['Name'] .'
                        企业负责人：'  . $touch['UserName'] .'
                        联系电话：'  . $touch['UserTel'] .'
                        摸排时间：' . $touch['TouchTime'] . '
                        预约时间：' . $item['SubscribeTime'] . '
                        预约回访内容：' . $item['Content']. '
                        状态：' . $this->statusName[$item['Status']],
                        'bgColor' => $bgcolor[$item['Status']],
                        'color' => $color[$item['Status']]
                    ];
                    $data[] = $temp;
                }else if(!empty($item['CompanyFileId'])){
                    if($item['CompanyId']==-1){
                        $company['Name'] = '【本企业】';
                    }else{
                        //查询企业与摸排表信息
                        $company = Company::get($item['CompanyId']); 
                    }
                    
                    $field = CompanyFile::get($item['CompanyFileId']);
                    $type = CompanyFileType::get($field['TypeId'])->value('Name');
                    // if(empty($touch)){continue;}
                    $temp = [
                        'id' => '103' . $item['SubscribeId'],
                        'type'=>'companyfile',
                        'SubscribeId'=>$item['SubscribeId'],
                        'opid'=>$item['CompanyFileId'],
                        'datetime' => substr($item['SubscribeTime'],0,13) . ':00',
                        'content' => '企业文件订阅提醒
                        企业名称：' .$company['Name'] .'
                        文件名称：'  . $field['Name'] .'
                        文件分类：'  . $type .'
                        预约时间：' . $item['SubscribeTime'] . '
                        状态：' . $this->statusName[$item['Status']],
                        'bgColor' => $bgcolor[$item['Status']],
                        'color' => $color[$item['Status']]
                    ];
                    $data[] = $temp;
                }
                
            }
        }
        return myok($data);
    }

    function wpjam_is_holiday($d){

        $url = 'http://apis.baidu.com/xiaogg/holiday/holiday?d='.$d;

        $response = wp_remote_get($url, array(

            'headers'=> array('apikey'=>'494969c1cb7d9d1b05960c7257750648'),

        ));

        $response = json_array($response['body'],true);

        return $response;

    }
}
